
#include <string.h>
#include "jxos_public.h"
#include "../platform/N76E003/soc_common/Common/hal.h"

void ir_rec_pin_init(void);
uint8_t ir_rec_pin_read(void);
void ir_timer_init(void);
void ir_timer_run(void);
void led_on(void);
void led_off(void);

#define store_data_base_addr		0x4780-0x80-0x80-0x80-0x80-0x80

#define IDLE_LEVLE		1
#define PULSE_LEVLE		!IDLE_LEVLE

#define CONTE_TIMEOUT	10000/40

uint8_t level_time_data[512] = {0};
uint16_t level_time_data_len = 0;
static uint16_t level_time_data_count = 0;

static uint16_t count;
static uint8_t current_level;
static uint8_t finish_flag;
uint8_t rx_lock;
void ir_rx_tick_handler(void)
{
	uint8_t new_level;

	if(rx_lock == 1){
		return;
	}
	if(finish_flag == 1){
		return;
	}
	
	new_level = ir_rec_pin_read();
	count++;
	
	if(new_level != current_level){
		level_time_data[level_time_data_count] = (count>>8);
		level_time_data[level_time_data_count+1] = (uint8_t)count;
		if(current_level == PULSE_LEVLE){
			level_time_data[level_time_data_count] += 0x80;
		}
		count = 0;
		level_time_data_count += 2;
		current_level = new_level;
	}
	else{
		if(count >= CONTE_TIMEOUT){
			if(level_time_data_count > 0){
				level_time_data_len = level_time_data_count;
				level_time_data_count = 0;
				count = 0;
				finish_flag = 1;
				rx_lock = 1;
			}
			else{
				count = 0;
			}
		}
	}
}

static uint16_t i;
static void ir_rx_task(uint8_t task_id, void * parameter)
{
	if(finish_flag == 1){
		led_on();
		flash_erase_page_aprom(store_data_base_addr);
		flash_erase_page_aprom(store_data_base_addr+128);
		flash_erase_page_aprom(store_data_base_addr+(128*2));
		flash_erase_page_aprom(store_data_base_addr+(128*3));
		flash_erase_page_aprom(store_data_base_addr+(128*4));
		
		flash_write_byte_aprom(store_data_base_addr, (uint8_t)(level_time_data_len>>8));
		flash_write_byte_aprom(store_data_base_addr+1, (uint8_t)(level_time_data_len));
		for(i = 0; i < level_time_data_len; i++){
			flash_write_byte_aprom(store_data_base_addr+2+i, level_time_data[i]);
			uart0_send_data_blocked(level_time_data[i]);
		}		
		led_off();
		finish_flag = 0;
	}
}

void  ir_rx_task_init(void)
{
	uart0_use_timer1_init(19200);
	clr_ES;           	//disable UART interrupt
	clr_REN;			//disable uart0 rx
	
	jxos_task_create(ir_rx_task, "ir_rx", 0);
	
	ir_rec_pin_init();
	ir_timer_init();
	ir_timer_run();
	
	count = 0;
	current_level = IDLE_LEVLE;
	finish_flag = 0;
	level_time_data_count = 0;
	rx_lock = 1;
	
	level_time_data_len = flash_read_byte(store_data_base_addr);
	level_time_data_len <<= 8;
	level_time_data_len += flash_read_byte(store_data_base_addr+1);
	
	if(level_time_data_len < 512){
		for(i = 0; i < level_time_data_len; i++){
			level_time_data[i] = flash_read_byte(store_data_base_addr+2+i);
		}	
	}
	else{
		level_time_data_len = 0;
	}
}